﻿using System;
using System.Web;

namespace Outlook.WorkItems.Extension.Manager.TeamPortal
{
    /// <summary>
    /// Helper for manage URI
    /// </summary>
    internal static class UriUtility
    {
        internal static Uri Combine(string baseUri, string relativePath, bool treatAbsolutePathAsRelative)
        {
            var uri = new Uri(baseUri);
            return Combine(uri, relativePath, treatAbsolutePathAsRelative);
        }

        internal static Uri Combine(Uri baseUri, string relativePath, bool treatAbsolutePathAsRelative)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            if (relativePath == null)
            {
                throw new ArgumentNullException("relativePath");
            }
            var builder = new UriBuilder(baseUri);
            var trimChars = new[] { '/' };
            builder.Path = builder.Path.TrimEnd(trimChars);
            builder.Path = VirtualPathUtility.AppendTrailingSlash(builder.Path);

            if (relativePath.StartsWith("/"))
            {
                if (!treatAbsolutePathAsRelative)
                {
                    throw new ArgumentException("AbsoluteVirtualPathNotAllowed", "relativePath");
                }
                relativePath = relativePath.TrimStart(trimChars);
            }
            return new Uri(builder.Uri, new Uri(relativePath, UriKind.Relative));
        }
    }
}
